package com.xh.bussiness.tiku.controller;

import com.xh.bussiness.tiku.bean.request.ChapterKnowledgeRequest;
import com.xh.bussiness.tiku.model.ChapterKnowledge;
import com.xh.bussiness.tiku.service.IChapterKnowledgeService;
import com.xh.bussiness.tiku.service.IKnowledgeService;
import com.xh.core.bean.AjaxResult;
import com.xh.core.constant.AjaxResultConstant;
import com.xh.core.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;


/**
 * <p>
 *
 * </p>
 *
 * @author Pitt zhang
 * @since 2019/4/8
 */
@Api(tags = "知识点接口")
@RestController
@RequestMapping("/tiku/chapterKnowledge")
public class ChapterKnowledgeController extends BaseController {

    @Autowired
    private IKnowledgeService knowledgeService;
    @Autowired
    private IChapterKnowledgeService chapterKnowledgeService;

    @ApiOperation("根据章节id查询知识点")
    @RequestMapping("/queryKnowledgeByChapterId")
    public AjaxResult queryKnowledgeByChapterId(String chapterId) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, knowledgeService.queryKnowledgeByChapterId(chapterId, null));
    }

    @RequestMapping("/batchSave")
    public AjaxResult batchSave(@RequestBody ChapterKnowledgeRequest request) {
        if (StringUtils.isEmpty(request.getChapterId()) || CollectionUtils.isEmpty(request.getKnowledgeIds())) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        if (request.getType().equals(2)) {
            chapterKnowledgeService.batchDelete(request.getChapterId(), null);
        }
        List<ChapterKnowledge> list = new ArrayList<>();
        for (String knowledgeId : request.getKnowledgeIds()) {
            ChapterKnowledge chapterKnowledge = new ChapterKnowledge();
            chapterKnowledge.setChapterId(request.getChapterId());
            chapterKnowledge.setKnowledgeId(knowledgeId);
            list.add(chapterKnowledge);
        }
        chapterKnowledgeService.batchInsert(list);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }

    @RequestMapping("/batchDelete")
    public AjaxResult batchDelete(@RequestBody ChapterKnowledgeRequest request) {
        chapterKnowledgeService.batchDelete(request.getChapterId(), request.getKnowledgeIds());
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }
}
